import {ADD_CART} from './mutation-types'
export default  {
	// 加购商品的方法，
	[ADD_CART](state, goodsinfo) {
		// 1，先去localStorage拿carts数据，存在拿出来，没有就通过商品id创建进去，有就通过id拿到count，然后count++
		if (localStorage.getItem("carts")) {
			state.carts = JSON.parse(localStorage.getItem("carts"))
		}
		if (state.carts[goodsinfo.id]) {
			state.carts[goodsinfo.id].count++
		} else {
			state.carts[goodsinfo.id] = {
				count: '1',
				checked: true,
				goods: goodsinfo
			}
		}
		// 加购后，更新localStorage的carts，然后在拿出来更新购物车的数据
		localStorage.setItem('carts', JSON.stringify(state.carts))
		// console.log("购买一个"+goodsinfo.title+'成功')
		state.carts = JSON.parse(localStorage.getItem("carts"))
	},
	// 全选按钮的点击
	clickSelectAll(state, flag) {
		for (let key in state.carts) {
			state.carts[key].checked = flag
			localStorage.setItem("carts", JSON.stringify(state.carts))
			state.carts = JSON.parse(localStorage.getItem("carts"))
		}
	},
	// 商品单选按钮
	clickOnechecked(state,id){
		state.carts[id].checked = !state.carts[id].checked
		localStorage.setItem("carts", JSON.stringify(state.carts))
		state.carts = JSON.parse(localStorage.getItem("carts"))
	},
	// 进入购物车页面需要展示加购的商品信息
	showCart(state) {
		// 从localStorage里拿数据
		state.carts = JSON.parse(localStorage.getItem("carts"))
	},
	// 如果改变了state.carts的数据，那么我需要及时将数据存进localStorage
	updateStorage(state) {
		localStorage.setItem("carts", JSON.stringify(state.carts))
		state.carts = JSON.parse(localStorage.getItem("carts"))
	},

	// 删除某一件商品
	delOnegoods(state, id) {
		delete state.carts[id]
	},
	// 清空购物车所有商品
	delAllgoods(state) {
		for (let key in state.carts) {
			delete state.carts[key]
		}
	},
	// 加减商品数量和输入框输入的方法
	cutGoodscount(state, obj) {
		console.log(state.carts[obj.id])
		state.carts[obj.id].count++
	},
	addGoodscount(state, obj) {
		console.log(state.carts[obj.id])
		state.carts[obj.id].count--
	},
	inputGoodscount(state, obj) {
		state.carts[obj.id].count = Number(obj.value)
	}

}
